import { defineStore } from "pinia";
import { ElNotification } from "element-plus";
import {
  getCompanyInfoApi,
  addCompanyApi,
  updateCompanyApi,
  deleteCompanyApi,
} from "@/apis/company";
import { ICompanyInfo } from "@/apis/company/type";

const useCompanyStore = defineStore("companyStore", {
  state: (): {
    companyInfo: ICompanyInfo[];
    isHasBusRegistNo: boolean;
  } => {
    return {
      companyInfo: [],
      isHasBusRegistNo: false,
    };
  },
  actions: {
    getInfo() {
      getCompanyInfoApi()
        .then(res => {
          if (res.code === 200) {
            this.companyInfo = [...res.data].reverse();
            ElNotification.success(`公司信息${res.message}!`);
          }
        })
        .catch(_ => {
          ElNotification.error("公司信息请求失败！！");
        });
    },
    addCompany(data: ICompanyInfo) {
      addCompanyApi(data)
        .then(res => {
          if (res.code == 200) {
            ElNotification.success(res.message);
          }
        })
        .catch(_ => {
          ElNotification.error("创建失败！！");
        });
    },
    updateCompany(id: string, data: ICompanyInfo) {
      updateCompanyApi(id, data)
        .then(res => {
          if (res.code == 200) {
            ElNotification.success(`公司信息更新${res.message}!`);
          }
        })
        .catch(_ => {
          ElNotification.error("更新失败！！");
        });
    },
    deleteCompany(id: string) {
      deleteCompanyApi(id)
        .then(res => {
          if (res.code == 200) {
            ElNotification.success(`公司信息删除${res.message}!`);
          }
        })
        .catch(_ => {
          ElNotification.error("删除失败！！");
        });
    },
    isHas(busRegistNo: string) {
      this.isHasBusRegistNo = this.companyInfo.some(
        item => item.busRegistNo === busRegistNo
      );
    },
  },
});

export default useCompanyStore;
